<!--演示屏幕共享视频流，本地录像的功能-->
<template>
  <div>
    <Row>
      <Col span="24">
        <div style="display: flex;height:500px">
          <div style="width:47%;height:100%; display: flex;flex-direction: column-reverse;justify-items: center;align-items: center">
            <div style="display: flex;justify-items: center;margin-top: 5px">
              <Button type="primary" @click="openCamera">打开摄像头</Button>
            </div>
            <div style="width:100%;height:100%;background-color: #0c0c0c">
              <video  id="previewVideo" ref="previewVideo" style="width:100%;height:100%" autoplay muted />
            </div>
          </div>
          <div style="width:6%;height:100%;display: flex;flex-direction: column;align-items: center;justify-content: center">
            <Button type="success" shape="circle" icon="md-call"></Button>
            <br>
            <br>
            <Button type="error" shape="circle" icon="md-call" ></Button>
          </div>
          <div style="width:47%;height:100%; display: flex;flex-direction: column-reverse;justify-items: center;align-items: center">
            <div style="display: flex;justify-items: center;margin-top: 5px">
              <Button type="primary" @click="startRecording">开始录像</Button>
              <Button type="error" @click="stopRecording">停止录像</Button>
            </div>
            <div style="width: 100%;height: 100%;background-color: #0c0c0c">
              <video id="recordVideo" ref="recordVideo" style="width:100%;height:100%" autoplay muted/>
            </div>
          </div>
        </div>
      </Col>
    </Row>
    <Row> <Col span="24">
      <span>{{logMsg}}</span>
      </Col>
    </Row>
    <Row>
      <Col span="24">
        <div style="display: flex;justify-content: center;align-items: center">
          <a id="downloadButton" ref="downloadButton" class="button">下载</a>
        </div>
      </Col>
    </Row>
  </div>
</template>
<script>
export default {
  components: {},
  data(){
    return{
      previewVideo:null,
      recorder:null,
      recordVideo:null,
      mediaStream:null,
      recordingMs:10000, //录制10秒

      logMsg:"",
      downloadButton:null,
    }
  },
  methods:{
    //延时N秒后开始
    wait(delayInMS) {
      return new Promise((resolve) => setTimeout(resolve, delayInMS));
    },
    startRecording_back(stream, lengthInMS) {
      console.log(">>>>>> startRecording() stream=%o",stream)
      //形如录制
      let recorder = new MediaRecorder(stream);
      let data = [];
      console.log(">>>>>> startRecording() recorder=%o",recorder)
      recorder.ondataavailable = (event) => data.push(event.data);

      recorder.start();
      this.logMsg = `${recorder.state} for ${lengthInMS / 1000} seconds…`

      //停止后要做的事
      let stopped = new Promise((resolve, reject) => {
        recorder.onstop = resolve;
        recorder.onerror = (event) => reject(event.name);
      });

      //lengthInMS 毫秒后停止录像
      let recorded = this.wait(lengthInMS).then(() => {
        if (recorder.state === "recording") {
          recorder.stop();
        }
      });
      console.log(">>>>>> startRecording() ")
      //在stop 和 recorded 产生 data
      return Promise.all([stopped, recorded]).then(() => data);
    },
    /**
     * 打开摄像头
     */
    async openCamera() {
      const _this = this;
      const stream = await navigator.mediaDevices.getDisplayMedia({
        video: true,
      });
      console.log(stream);
      _this.previewVideo.srcObject = stream;
      _this.previewVideo.captureStream = _this.previewVideo.captureStream || _this.previewVideo.mozCaptureStream;

      /*      const constraints = { audio: true, video: { width: 1280, height: 720 } };
            navigator.mediaDevices.getUserMedia(constraints).then(stream=>{
              _this.previewVideo.srcObject = stream;
              _this.previewVideo.captureStream = _this.previewVideo.captureStream || _this.previewVideo.mozCaptureStream;

            });*/
    },

    /**
     * 开始录像
     */
    startRecording(){
      const mediaStream =  this.previewVideo.captureStream();
      const mime = MediaRecorder.isTypeSupported("video/webm;codecs=h264")
        ? "video/webm;codecs=h264"
        : "video/webm";
      console.log(mime);

      this.recorder = new MediaRecorder(mediaStream,{ mimeType: mime });
      let chunks = [];
      this.recorder.ondataavailable = (event) => {
        console.log(event.data);
        chunks.push(event.data);
      }
      this.recorder.onstop=(stream)=>{
        console.log("onStop")
        const blob = new Blob(chunks, { type: chunks[0].type });
        const url = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = "video.mp4";

        //document.removeElement(a)
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      }
      this.recorder.start();
    },

    /**
     * 结束录像
     */
    stopRecording(){
      const stream = this.previewVideo.srcObject;
      stream.getTracks().forEach((track) => track.stop());
      this.recorder.stop();
    },


    start_back(){
      this.previewVideo = this.$refs.previewVideo;
      const _this = this;
      const constraints = { audio: true, video: { width: 1280, height: 720 } };
      navigator.mediaDevices.getUserMedia(constraints).then(function(stream) {
        //打开摄像和话筒成功
        _this.previewVideo.srcObject = stream;
        //下载链接
        _this.downloadButton.href = stream;
        //录像的Stream
        _this.previewVideo.captureStream = _this.previewVideo.captureStream || _this.previewVideo.mozCaptureStream;

        return new Promise((resolve) => (_this.previewVideo.onplaying = resolve));
      }).then(()=>{
        const mediaStream =  _this.previewVideo.captureStream();
        console.log(">>>>>> after start(),stream=%o,recordingMs=%o",mediaStream,_this.recordingMs)
        //开始预览
        _this.startRecording(mediaStream, _this.recordingMs)
      }).then((recordedChunks) => {
        console.log(">>>>>> recordedChunks-%o",recordedChunks)
        let recordedBlob = new Blob(recordedChunks, { type: "video/webm" });

        _this.recordVideo.src = URL.createObjectURL(recordedBlob);
        //加到这里，只要点download就可以下载了
        _this.downloadButton.href = _this.recordVideo.src;
        _this.downloadButton.download = "RecordedVideo.webm";

        _this.logMsg =`Successfully recorded ${recordedBlob.size} bytes of ${recordedBlob.type} media.`
        //let a = document.createElement('a');
      }).catch((error) => {
        if (error.name === "NotFoundError") {
          _this.logMsg ="Camera or microphone not found. Can't record.";
        } else {
          _this.logMsg =error;
        }
      });
    }

  },
  mounted() {
    this.previewVideo = this.$refs.previewVideo;
    this.recordVideo = this.$refs.recordVideo;
    this.downloadButton = this.$refs.downloadButton;
  }
}

</script>
<style lang="less">

</style>
